import React, { Component } from 'react';
import { View, Platform, TouchableOpacity, ListView, Text, StyleSheet, RefreshControl, Alert, SafeAreaView } from 'react-native';
import { createMaterialTopTabNavigator, createAppContainer } from 'react-navigation';
import { MaterialTopTabBar } from 'react-navigation-tabs';
import constants from '../../utils/constants';
import Icon from 'react-native-vector-icons/FontAwesome';
import { SwipeListView } from 'react-native-swipe-list-view';
import { Flex, Toast } from 'antd-mobile-rn';
import api from '../../utils/api';
import moment from 'moment';
import taskService from '../../service/taskService';

const styles = StyleSheet.create({
    rowStyle: {
        alignItems: 'center',
        backgroundColor: '#ffffff',
        borderBottomColor: '#ddd',
        borderBottomWidth: 1,
        flexWrap: 'wrap',
        flexDirection: "row",
        padding: 10,
        paddingLeft: 20,

    },
    rowBack: {
        alignItems: 'center',
        backgroundColor: "transparent",
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'space-between',
        paddingLeft: 15,
        borderBottomColor: '#ddd',
        borderBottomWidth: 1,
    },
    backRightBtn: {
        alignItems: 'center',
        bottom: 0,
        justifyContent: 'center',
        position: 'absolute',
        top: 0,
        width: 75
    },
    backRightBtnLeft: {
        backgroundColor: 'blue',
        right: 75
    },
    backRightBtnRight: {
        backgroundColor: constants.themeColor,
        right: 0
    },
})

class Starting extends Component {

    static navigationOptions = (e) => {
        return {
            title: "进行中",
        }
    }

    state = {
        taskList: [],
        refreshing: false,
        hasData: true
    }

    constructor(props) {
        super(props);
        this.ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
    }

    loadDataList = () => {
        this.setState({
            refreshing: true
        })

        try {
            api({
                url: "/task/inProgressList",
                method: "POST"
            }).then(data => {
                if (!data.success) {
                    this.setState({
                        refreshing: false
                    })
                    return;
                }
                this.setState({
                    taskList: data.result,
                    refreshing: false,
                    hasData: data.result.length == 0
                })
            }).catch((data) => {
                this.setState({
                    refreshing: false
                })
            })
        } catch (error) {
            this.setState({
                refreshing: false
            })
        }

    }

    componentDidMount() {
        this.loadDataList();
    }

    render() {
        const { app } = this.props.screenProps;
        console.log("TaskList app ", app);
        const showNoData = this.state.hasData ? (
            <View style={{ alignItems: "center", padding: 20 }}>
                <Text style={{ color: "#ccc" }}>没有数据...</Text>
            </View>
        ) : undefined;
        return (
            <View style={{ flex: 1, backgroundColor: "#fff" }}>
                {showNoData}
                <SwipeListView

                    refreshControl={
                        <RefreshControl
                            colors={[constants.themeColor]}
                            refreshing={this.state.refreshing}
                            onRefresh={() => {
                                this.loadDataList();
                            }}
                            progressBackgroundColor="#fff"

                        />
                    }

                    enableEmptySections={true}
                    rightOpenValue={-150}
                    disableRightSwipe={true}
                    dataSource={this.ds.cloneWithRows(this.state.taskList)}
                    renderRow={(data, secId, rowId, rowMap) => (
                        <View style={[styles.rowStyle, rowId == 0 ? {
                            borderTopColor: '#ddd',
                            borderTopWidth: 1,
                        } : {}]}>
                            <View style={{ width: "40%" }}>
                                <Text style={{ fontSize: 18, fontWeight: "bold" }}>{data.taskName}</Text>
                            </View>
                            <View style={{ width: "60%" }}>
                                <View>
                                    <Text>{moment(data.startDate).format("YYYY.MM.DD")} - {moment(data.endDate).format("YYYY.MM.DD")}</Text>
                                </View>
                                <View>
                                    <Text>{data.remainWeek}</Text>
                                </View>
                                <View>
                                    <Text>提醒:{data.isRemain == 0 ? "关闭" : "开启"}</Text>
                                </View>
                                {/* <View>
                                    <Text>.打卡30次</Text>
                                </View>
                                <View>
                                    <Text>.共学习130个小时</Text>
                                </View> */}
                            </View>
                        </View>
                    )}

                    renderHiddenRow={(data, secId, rowId, rowMap) => {
                        const rowKey = `${secId}${rowId}`;
                        // if (data.status == 1) {
                        //     return undefined;
                        // }
                        const nowDate = moment(moment(new Date().getTime()).format("YYYY-MM-DD"), "YYYY-MM-DD").toDate();
                        return (
                            <View style={styles.rowBack}>
                                <TouchableOpacity style={[styles.backRightBtn, { right: 75, backgroundColor: "#ddd", }]} onPress={() => {
                                    // console.log("rowMap::",rowMap);
                                    // console.log("role::",rowMap[rowKey]);
                                    const row = rowMap[rowKey];
                                    if (row) {
                                        row.closeRow();
                                    }

                                    // if (data.startDate < nowDate.getTime()) {
                                    //     Toast.info("不可编辑今日之前的任务")
                                    //     return;
                                    // }

                                    app.navigate("TaskEdit", {
                                        isEdit: true,
                                        taskId: data.taskId,
                                        back: () => {
                                            console.log("TaskEdit back");
                                            this.loadDataList();
                                            const back = app.getParam("homeBack");
                                            if (back) {
                                                back();
                                            }
                                        }
                                    })

                                    //this.removeTask(data, rowId)
                                }}>
                                    <Text style={{ color: "#78798F" }}>编辑</Text>
                                </TouchableOpacity>
                                <TouchableOpacity style={[styles.backRightBtn, styles.backRightBtnRight]} onPress={() => {
                                    // console.log("rowMap::",rowMap);
                                    // console.log("role::",rowMap[rowKey]);
                                    const row = rowMap[rowKey];
                                    if (row) {
                                        row.closeRow();
                                    }

                                    Alert.alert("提示", "是否删除该任务?", [
                                        { text: "取消" },
                                        {
                                            text: "确定", onPress: () => {
                                                console.log("data:", data, rowId);
                                                //this.state.taskList.splice(rowId, 1);
                                                // this.setState({
                                                //     taskList: taskList
                                                // })
                                                taskService.remove(data.taskId).then(data => {
                                                    this.loadDataList();
                                                    const back = app.getParam("homeBack");
                                                    if (back) {
                                                        back();
                                                    }

                                                })

                                            }
                                        },

                                    ], { cancelable: true })
                                    //this.removeTask(data, rowId)
                                }}>
                                    <Text style={{ color: "#fff" }}>删除</Text>
                                </TouchableOpacity>
                            </View>
                        );
                    }}
                />


            </View>
        )
    }

}

class Complete extends Component {

    static navigationOptions = (e) => {
        return {
            title: "已完成",
        }
    }

    state = {
        taskList: [],
        refreshing: true,
        hasData: true,
    }

    constructor(props) {
        super(props);
        this.ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
    }

    loadDataList = () => {
        this.setState({
            refreshing: true
        })
        api({
            url: "/task/completedList",
            method: "POST"
        }).then(data => {
            this.setState({
                taskList: data.result,
                refreshing: false,
                hasData: data.result.length == 0
            })
        }).catch((data) => {
            this.setState({
                refreshing: false
            })
        })
    }

    componentDidMount() {
        this.loadDataList();
    }

    render() {

        const showNoData = this.state.hasData ? (
            <View style={{ alignItems: "center", padding: 20 }}>
                <Text style={{ color: "#ccc" }}>没有数据...</Text>
            </View>
        ) : undefined;

        return (
            <View style={{ flex: 1, backgroundColor: "#fff" }}>

                {showNoData}

                <SwipeListView

                    refreshControl={
                        <RefreshControl
                            colors={[constants.themeColor]}
                            refreshing={this.state.refreshing}
                            onRefresh={() => {
                                this.loadDataList();
                            }}
                            progressBackgroundColor="#fff"

                        />
                    }

                    enableEmptySections={true}
                    rightOpenValue={-150}
                    disableRightSwipe={true}
                    dataSource={this.ds.cloneWithRows(this.state.taskList)}
                    renderRow={(data, secId, rowId, rowMap) => (
                        <View style={[styles.rowStyle, rowId == 0 ? {
                            borderTopColor: '#ddd',
                            borderTopWidth: 1,
                        } : {}]}>
                            <View style={{ width: "40%" }}>
                                <Text style={{ fontSize: 18, fontWeight: "bold" }}>{data.taskName}</Text>
                            </View>
                            <View style={{ width: "60%" }}>
                                <View>
                                    <Text>{moment(data.startDate).format("YYYY.MM.DD")} - {moment(data.endDate).format("YYYY.MM.DD")}</Text>
                                </View>
                                <View>
                                    <Text>{data.remainWeek}</Text>
                                </View>

                                <View>
                                    <Text>打卡{data.completedCount}次</Text>
                                </View>
                                <View>
                                    <Text>共学习{data.learndTime}个小时</Text>
                                </View>
                            </View>
                        </View>
                    )}


                />


            </View>
        )
    }
}


const TabNavigator = createMaterialTopTabNavigator(
    {
        Starting: Starting,
        Complete: Complete,
    },
    {

        lazy: true,
        tabBarComponent: (props) => {
            const { app } = props.screenProps;
            return (
                <View
                    style={{
                        backgroundColor: '#fff',
                        alignItems: "center",
                        position: "relative",
                    }}
                >

                    <MaterialTopTabBar {...props} jumpToIndex={() => { }} />
                    <View style={{ position: "absolute", width: 50, height: 30, left: 20, top: 10 }}>
                        <TouchableOpacity onPress={() => {
                            app.goBack();
                        }}>
                            <Icon size={30} name="angle-left"></Icon>
                        </TouchableOpacity>

                    </View>
                </View>
            )
        },
        tabBarOptions: {
            activeTintColor: constants.themeColor,
            inactiveTintColor: constants.themeColor,
            labelStyle: {
                fontSize: 18,


            },
            tabStyle: {
                width: 120
            },
            style: {
                backgroundColor: "#fff",
                borderBottomWidth: 0,
                shadowOpacity: 0,
                elevation: 0,
                width: 250,
                alignContent: "center"
            },
            indicatorStyle: {
                backgroundColor: constants.themeColor,
                width: 45,
                marginLeft: 38,
                marginBottom: 5,

            }
        },
        swipeEnabled: false
    }
);

const App = createAppContainer(TabNavigator);


export default class TaskList extends Component {

    static navigationOptions = (e) => {
        return {
            title: "",
            header: () => {
                return undefined;
            }
        }
    }

    constructor(props) {
        super(props);
        this.navigation = this.props.navigation;

    }

    render() {


        return (
            <SafeAreaView style={{ flex: 1 }}>
                <View style={{ flex: 1, paddingTop: Platform.OS === "android" ? 0 : (parseFloat(Platform.Version) < 11 ? 20 : 0) }}>
                    <App screenProps={{ app: this.navigation }} />
                </View>
            </SafeAreaView>

        )
    }
}

